# -*- coding:utf-8 -*-

from utils import DbSession

class MonitorTask(object):

    def __init__(self, alarm, scheduler, context):
        self.alarm = alarm
        self.context = context
        self.taskscheduler = scheduler
        self.job = None
        self.state = ""

    def docheck(self):
        '''execute check task'''

        raise Exception("Not Implemented!")

    def getservicestatus(self):
        '''get current service status'''

        serviceid = self.context["id"]
        with DbSession() as db:
            sql = "select service_status from m_services where id=%s"
            service = db.selectone(sql, (serviceid, ))
            if service:
                return service[0]

    def isnew(self):
        return self.getservicestatus() == "NEW"

    def isstoped(self):
        return self.getservicestatus() == "STOP"

    def isrunning(self):
        return self.getservicestatus() == "RUNNING"

    def updatestatus(self, status):
        '''update task status'''

        if not self.getservicestatus():
            try:
                self.taskscheduler.unschedule_job(self.job)
                return
            except KeyError:
                print("cancel not existed job")

        serviceid = self.context["id"]

        with DbSession() as db:
            sql = "update m_services set service_status ='%s' where id = %s"
            db.update(sql, (status, serviceid))

    def firealarm(self, alarminfo):
        self.updatestatus("STOP")
        self.alarm.send(alarminfo)

    def schedule(self):
        interval = int(self.context["checkinterval"])
        self.job = self.taskscheduler.add_interval_job(self.docheck, seconds = interval)
        return self

    def unschedule(self):
        try:
            self.taskscheduler.unschedule_job(self.job)
        except KeyError:
            print("no such job in job store")

    @staticmethod
    def start(servicetype, description, alarm, scheduler):
        try:
            from plugin.PingCheck import PingCheckTask
            from plugin.HttpCheck import HttpCheckTask
            taskdict = {"PING":PingCheckTask,"HTTP":HttpCheckTask}
            task = taskdict[servicetype](alarm, scheduler, description)
            return task.schedule()
        except:
            print(servicetype+" Plug-in is not installed")
